package ;
import hxphp.oo.gd.GD;
import hxphp.oo.gd.GDImage;
import php.db.Object;
import php.db.Manager;
import php.FileSystem;
import php.io.File;
import php.Sys;
import php.Web;

/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Image extends Object
{

	static var thumbSize = 240;
	public static var thumbsDir = "thumbs/";
	static var TABLE_NAME = "Images";
	
	static function RELATIONS()
	{
		return [{props:"parent", key: "catId", manager: Cats.manager}];
	}
	
	public var id:Int;
	public var catId:Int;
	public var isPrimary:Bool;
	public var url:String;
	public var width:Int;
	public var height:Int;	
	public var parent(dynamic, dynamic):Cats;
	
	public static var manager = new php.db.Manager<Image>(Image);
	
	public static function getAll4(cid:Int):List<Image>
	{
		return manager.objects("SELECT * FROM Images WHERE catID = '" +cid + "'", true);
	}
	
	public static function remove(iid:Int):Bool
	{
		var img:Image = manager.get(iid);
		if (img == null)
			return false;
		img.delete();
		return true;
	}
	
	public static function saveFile(tmpname, filename, destinationDir='img/katzen/'):String
	{
		//Main.errLog(Web.getCwd() + ' / ' + destinationDir + filename + Std.string(FileSystem.isDirectory(destinationDir)));
		if ( untyped __call__("move_uploaded_file",  tmpname, destinationDir + filename))
			return destinationDir + filename;
		return null;
	}
	
	public static function createThumb(filename, ?maxSize:Int)
	{
		var info:GDImageSizeResult = GD.getImageSize(filename);
		//Main.errLog(filename + ' image type:' + info.type);
		if (maxSize == null)
			maxSize = thumbSize;
		var scale:Float = info.width > info.height ? maxSize / info.width : maxSize / info.height;
		var thumb:GDImage = switch(info.type)
		{
			case GDImageType.JPG:
			GDImage.createFromJpeg(filename);
			case GDImageType.PNG:
			GDImage.createFromPng(filename);
			case GDImageType.GIF:
			GDImage.createFromGif(filename);
			default:
		}
		thumb.resize(Math.round(info.width * scale), Math.round(info.height * scale));
		var r = ~/([\w\-]*\/)+/;
		filename = (r.match(filename) ?
			r.replace(filename, r.matched(0) + thumbsDir):
			thumbsDir + filename);
		switch(info.type)
		{
			case GDImageType.JPG:
			thumb.outputJpeg(filename);
			case GDImageType.PNG:
			thumb.outputPng(filename);
			case GDImageType.GIF:
			thumb.outputGif(filename);
			default:
		}
	}
	
	public static function setPrimary(iid:Int, cid:Int)
	{
		var siblings:List<Image> = manager.objects("SELECT * FROM Images WHERE catID = '" +cid + "'", true);
		for (s in siblings)
		{
			var current = s.isPrimary;
			if (s.id == iid)
				s.isPrimary = true;				
			else
				s.isPrimary = false;
			if(current != 	s.isPrimary)//VALUE CHANGED
				s.update();
		}
	}

}